package org.lqk.pool.netty;

import io.netty.channel.Channel;
import io.netty.channel.socket.SocketChannel;
import org.apache.commons.pool2.impl.GenericObjectPool;
import org.lqk.pool.socket2.PooledSocketConnectionFactory;
import org.lqk.pool.socket2.SocketConnection;
import org.lqk.pool.socket2.SocketConnectionConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

/**
 * Created by bert on 16-5-9.
 */
@Component
public class GenericSocketChannelPool implements InitializingBean,DisposableBean{
    // 连接池
    private GenericObjectPool<Channel> objectPool;
    @Autowired
    private PooledSocketChannelFactory pooledSocketChannelFactory;
    private static Logger log = LoggerFactory.getLogger(GenericSocketChannelPool.class);
    public Channel borrowSocketChannel() throws Exception {
        log.debug("borrowSocketChannel...");
        return objectPool.borrowObject();
    }

    public void returnSocketChannel(Channel channel) {
        log.debug("returnSocketChannel...");
        objectPool.returnObject(channel);

    }

    @Override
    public void afterPropertiesSet() throws Exception {
        objectPool = new GenericObjectPool<Channel>(pooledSocketChannelFactory);
    }

    @Override
    public void destroy() throws Exception {
        objectPool.close();
    }
}
